import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getCurrentLanguage, setLanguage } from '../i18n'

export function useLanguage() {
  const { locale } = useI18n()
  const currentLanguage = ref(getCurrentLanguage())

  // 切换语言
  const changeLanguage = (lang: any) => {
    setLanguage(lang)
    currentLanguage.value = lang
    
    // 保存到系统配置
    if (window.request) {
      window.request('/system/config/setConfig', {
        method: 'POST',
        body: { lang }
      }).catch(error => {
        console.warn('Failed to save language setting:', error)
      })
    }
  }

  // 从系统配置加载语言设置
  const loadLanguageFromConfig = async () => {
    try {
      if (window.request) {
        const config = await window.request('/system/config/getConfig', {
          method: 'GET'
        })
        if (config?.lang) {
          changeLanguage(config.lang)
        }
      }
    } catch (error) {
      console.warn('Failed to load language from config:', error)
      // 如果加载失败，使用localStorage中的设置
      const savedLang = localStorage.getItem('language')
      if (savedLang) {
        changeLanguage(savedLang)
      }
    }
  }

  // 监听语言变化
  watch(currentLanguage, (newLang) => {
    if (newLang !== locale.value) {
      setLanguage(newLang)
    }
  })

  return {
    currentLanguage,
    changeLanguage,
    loadLanguageFromConfig
  }
} 